package org.lds.logger.config.appender.rolling;

import lombok.Getter;
import org.lds.logger.config.LifeCycle;
import org.lds.logger.config.appender.FileAppender;
import org.lds.logger.exception.LoggerException;

import java.io.File;
import java.util.regex.Pattern;

@Getter
public abstract class AbstractRollingStrategy implements RollingStrategy, LifeCycle {
    /**
     * 滚动文件名前缀
     */
    private String rollingFileNamePrefix;
    /**
     * 扩展名
     */
    private String expandName;
    /**
     * 文件名
     */
    private String fileName;
    /**
     * 携带扩展名的文件名
     */
    private String fileNameWithExpandName;
    /**
     * 文件名格式
     */
    private Pattern pattern;
    /**
     * 文件
     */
    private File file;

    private FileAppender fileAppender;

    public void setFileAppender(FileAppender fileAppender) {
        this.fileAppender = fileAppender;
    }

    protected void setFile(File file) {
        this.file = file;
    }

    @Override
    public void initialize() {
        setAttributes();
    }

    private void setAttributes() {
        String destination = fileAppender.getDestination();

        int lastDot = destination.lastIndexOf('.');
        if (lastDot != -1) {
            rollingFileNamePrefix = destination.substring(0, lastDot);
            expandName = destination.substring(lastDot);
        }

        int lastSlash = destination.lastIndexOf('/');
        if (lastSlash != -1) {
            fileNameWithExpandName = destination.substring(lastSlash + 1);
            fileName = fileNameWithExpandName.substring(0, fileNameWithExpandName.indexOf(expandName));

            pattern = Pattern.compile(fileName + ".*" + expandName);
        }

        try {
            file = new File(destination);
        } catch (Throwable e) {
            throw new LoggerException(destination + " file not found");
        }
    }
}
